/**
 * 全局变量
 */
var currentScale = 8;//表示当前zoom级别
//用来识别是哪个分类的菜单按钮被点击了
var orignalCategoryNameEncode;
var currentEditEntry;
var selectedCategoryIds= new Array(); //用来记录有哪些分类被选中了
var selectedCategories = new Object();

function gotoDate(date){
    if (window.tl) {
        for (ii = 0; ii < tl.getBandCount(); ii++) {
            tl.getBand(ii).setCenterVisibleDate(date);
        }
    }
}

function zoomTimeline(scale){
	log('zoomTimeline('+scale+')');
	centerX = tl.getBand(0).getEther().dateToPixelOffset(tl.getBand(0).getCenterVisibleDate());
	var loc= new Object();
	loc.x=centerX;
	loc.y=0;
	
    if (scale < currentScale) {
		zoomIn=true;
		r=currentScale;
		l=scale;
    }else {
		zoomIn=false;
		l=currentScale;
		r=scale;
	}
	
	for (var ii = 0; ii < r-l; ii++) {
		log('zoom '+ii);
//		debugger
        //centerX-=SimileAjax.DOM.getPageCoordinates(tl.getBand(0)._div).left;//.left 通常为负数
        //centerX -= tl.getBand(0).getViewOffset();//.left 通常为负数
        doZoomTimeLine(loc ,zoomIn);
	}
    
}
function doZoomTimeLine(loc,zoomIn)
{
//ning :用一个for循环包围

	if (currentScale==1 && zoomIn)
		return;
	if (currentScale==20 && !zoomIn)
		return;

	log('doZoom at Loc x:'+loc.x+'y:'+loc.y);
	
    for (ii = 0; ii < tl.getBandCount(); ii++) {
        innerFrame = tl.getBand(ii)._div;// ning: important 分别替换各个 band
		if (ii == 0 )//by ning:
			tl.getBand(ii).zoom(zoomIn, loc.x, loc.y, innerFrame);// modify by ning :原来是timeline.zoom
        else 
			tl.getBand(ii).zoom2(zoomIn, loc.x, loc.y, innerFrame);// modify by ning :原来是timeline.zoom
    }
	tl.getBand(1)._onHighlightBandScroll();//只能用这种方式同步了。。注意如果改用多个band的话，这里也要改。
    tl.paint();
	if (zoomIn)
		currentScale--;
	else 
		currentScale++;
}

function changeTimelineDefaultConfig(){

    Timeline._Band.prototype.zoom2 = function(zoomIn, x, y, target){
        if (!this._zoomSteps) {
            // zoom disabled
            return;
        }
        
        // shift the x value by our offset
        x += this._viewOffset;
        
        var zoomDate = this._ether.pixelOffsetToDate(x);
        var netIntervalChange = this._ether.zoom(zoomIn);
        this._etherPainter.zoom(netIntervalChange);
        /*& by ning
        // shift our zoom date to the far left
        this._moveEther(Math.round(-this._ether.dateToPixelOffset(zoomDate)));
        // then shift it back to where the mouse was
        this._moveEther(x);
        */
    };
	
    Timeline._Band.prototype._onMouseScroll = function(innerFrame, evt, target){
        var delta = 0;
        if (evt.wheelDelta) {
            delta = evt.wheelDelta / 120;
        }
        else 
            if (evt.detail) {
                delta = -evt.detail / 3;
            }
		var loc = SimileAjax.DOM.getEventRelativeCoordinates(evt, innerFrame);
		
		if (delta != 0) {
			var zoomIn;
			if (delta > 0) 
				zoomIn = true;
			if (delta < 0) 
				zoomIn = false;
			doZoomTimeLine(loc, zoomIn);
			dijit.byId('slider2').setValue(currentScale);
		}
        // prevent bubble
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        evt.cancelBubble = true;
        
        // prevent the default action
        if (evt.preventDefault) {
            evt.preventDefault();
        }
        evt.returnValue = false;
    };

	Timeline._Band.prototype._onDblClick = function(innerFrame, evt, target){
		var coords = window.SimileAjax.DOM.getEventRelativeCoordinates(evt, innerFrame);
		clickedDate = tl.getBand(0)._ether.pixelOffsetToDate(coords.x +
		this._viewOffset);
		//    window.alert(clickedDate);
		//TODO:检查是否已近login了。（权限管理）
		showCreateEventDialog(clickedDate)	;
		
	};
    
    Timeline.DefaultEventSource.Event.prototype.fillInfoBubble = function(elmt, theme, labeller){
        var doc = elmt.ownerDocument;
        
        var title = this.getText();
        var link = this.getLink();
        var image = this.getImage();// removed by ning
        
        var divTitle = doc.createElement("div");
        var textTitle = doc.createTextNode(title);
        
        divTitle.appendChild(textTitle);
        theme.event.bubble.titleStyler(divTitle);
        elmt.appendChild(divTitle);
        
        var divBody = doc.createElement("div");
        if (this._description) 
            divBody.innerHTML = this._description;
        theme.event.bubble.bodyStyler(divBody);
        elmt.appendChild(divBody);
        
        var divTime = doc.createElement("div");//TODO:MODIFY
//        this.fillTime(divTime, labeller); // fill time format by myself (ning)
		//add by ning:
		var span = document.createElement("span");
        span.innerHTML = formatDate(this._start)+" 到 "+formatDate(this._end);
		
		divTime.appendChild(span);		
        //end 
        theme.event.bubble.timeStyler(divTime);
        elmt.appendChild(divTime);
        
        var divWiki = doc.createElement("div");
        //        this.fillWikiInfo(divWiki);
        
        var a = document.createElement("span");
        
        a.innerHTML = "删除";
        a.className = "bubblelink";
		a.eventID = this.getID();
		var eventID = this.getID();//NOTICE:用这种方法传参数。
        var onDel = function(){//del event ,TODO :

			var event = Cache.Events.getById(eventID);
			event.deleteEntry(function (rst){
	            log('event deleted!');
	            Cache.Events.remove(eventID);
				Cache.Events.synchronizeToTimeline();
			}, handleError);
        };
		
		a.onclick = function(){
			onDel();
		    this.style.display = "none";//TODO : close bubble
			for (ii = 0; ii < tl.getBandCount(); ii++) {
				tl.getBand(ii).closeBubble();
			}

		}
		divWiki.appendChild(document.createTextNode("["));divWiki.appendChild(a);
        divWiki.appendChild(document.createTextNode("]"));
        theme.event.bubble.wikiStyler(divWiki);
        
        
        a = document.createElement("span");
        a.innerHTML = "编辑";
        a.className = "bubblelink";
        a.onclick = function(){
			for (ii = 0; ii < tl.getBandCount(); ii++) {
				tl.getBand(ii).closeBubble();
			}
        	showEditEventDialog(eventID);
//			tl.paint();
        }
        divWiki.appendChild(document.createTextNode("["));
        divWiki.appendChild(a);
        divWiki.appendChild(document.createTextNode("]"));
        theme.event.bubble.wikiStyler(divWiki);
        
        
        elmt.appendChild(divWiki);
    }

}


function showCreateEventDialog(clickedDate)
{
	dijit.byId('addEventDialog').show();
      
	dijit.byId('startDate').setValue(clickedDate);
	dijit.byId('endDate').setValue(clickedDate);
	dijit.byId('startTime').setValue(clickedDate);
	dijit.byId('endTime').setValue(clickedDate);
	var list = document.getElementById('eventCategory');
	var s = ""
	calendarEntries=Cache.Calendars.getAllCalendars();
	for (ii = 0; ii < calendarEntries.length; ii++) {
		var calendarTitle = calendarEntries[ii].getTitle().getText();
		var calendarUrl = calendarEntries[ii].getAtomAlternateLink().getHref();
		//			calendarEntries[ii].getId().getValue();
		s += "<option value='" + getCalendarId(calendarEntries[ii])+ "' >" + calendarTitle + "</option>";
	}
	list.innerHTML = s;
	form1 =  dijit.byId('addEventDialog');
	form1.execute=onCreateEvent;
}
function showEditEventDialog(eventID)
{
	var entry= Cache.Events.getById(eventID);
	dijit.byId('addEventDialog').show();
	var start = entry.getTimes()[0].getStartTime().getDate();
	var end = entry.getTimes()[0].getEndTime().getDate();
	var title =entry.getTitle().getText();
	var content = entry.getContent().getText();
	
	dijit.byId('startDate').setValue(start);
	dijit.byId('endDate').setValue(end);
	dijit.byId('startTime').setValue(start);
	dijit.byId('endTime').setValue(end);
	dijit.byId('title').setValue(title);
	
	dijit.byId('content').setValue(content);
	
	var list = document.getElementById('eventCategory');
	var s = ""
	calendarEntries=Cache.Calendars.getAllCalendars();
	for (ii = 0; ii < calendarEntries.length; ii++) {
		var calendarTitle = calendarEntries[ii].getTitle().getText();
		var calendarUrl = calendarEntries[ii].getAtomAlternateLink().getHref();
		if (eventID.indexOf(calendarUrl)>=0 )
			s += "<option value='" + getCalendarId(calendarEntries[ii])+ "' selected='true'>" + calendarTitle + "</option>";
		else 
			s += "<option value='" + getCalendarId(calendarEntries[ii])+ "' >" + calendarTitle + "</option>";
	}
	list.innerHTML = s;
	form1 =  dijit.byId('addEventDialog');
	form1.currentEditEventID=eventID;
	form1.execute=onEditEvent;
	
}

function formatDate (d)
{
	return dojo.date.locale.format(d, {selector:'date', datePattern:'yyyy-MM-dd HH:mm'});
}
function onEditEvent()
{
	var	eventID=form1.currentEditEventID
	var event = Cache.Events.getById(eventID);
	event.deleteEntry(function (rst){
        log('event deleted!');
        Cache.Events.remove(eventID);
		Cache.Events.synchronizeToTimeline();
	}, handleError);
	Cache.Events.remove(eventID);
	form1 =  dijit.byId('addEventDialog');
	log ("edit "+form1.currentEditEventID);
	
	onCreateEvent();
}
function onCreateEvent(){
    var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
    calendarEntry=getCalendarById(dojo.byId("eventCategory").value);
	var feedUri = calendarEntry.getAtomAlternateLink().getHref()
	var color = calendarEntry.getColor().getValue();
//    var feedUri = dojo.byId("eventCategory").value;
	//'http://www.google.com/calendar/feeds/default/private/full';
    
    var entry = new google.gdata.calendar.CalendarEventEntry();
    var when = new google.gdata.When();
    
    var where = new google.gdata.Where();
    var title = document.getElementById('title').value;
    var content = document.getElementById('content').value;
	
    var startDate = dijit.byId('startDate').value;
    var endDate = dijit.byId('endDate').value;
    var startTime = dijit.byId('startTime').value;
    var endTime = dijit.byId('endTime').value;
    var location = document.getElementById('location').value;

    var start = startDate;
    var end = endDate;//+endTime; 
	start.setHours (startTime. getHours() );
	start.setMinutes (startTime. getMinutes ());
	start.setSeconds(startTime.getSeconds());
	
	end.setHours (endTime. getHours() );
	end.setMinutes (endTime. getMinutes ());
	end.setSeconds(endTime.getSeconds());
	
    when.setStartTime(start);
    when.setEndTime(end);
    
    where.setValueString(location);     //设置地点//TODO :TEST
    
    entry.setTitle(google.gdata.Text.create(title));
    entry.setContent(google.gdata.Text.create(content));
    entry.addTime(when);
    entry.addLocation(where);
    
    var callback = function(result){
        log('event created!');
		addEventEntriesToTimeline([result.entry,]);//TO DO :MODIFY COLOR
		Cache.Events.addEvent(result.entry);//result entry 中id已近更新了。
    }
    var handleError = function(error){
        log(error);
    }
    calendarService.insertEntry(feedUri, entry, callback, handleError, google.gdata.calendar.CalendarEventEntry);
}

function initTimeline(){

    changeTimelineDefaultConfig();
    gEventSource = new Timeline.DefaultEventSource();
    //    showCategoryCtl();
    var theme = Timeline.ClassicTheme.create();
    theme.event.bubble.width = 320;
    theme.event.bubble.height = 220;
    //    theme.mouseWheel = 'zoom'; // 'default', 'zoom', 'scroll'
    theme.mouseWheel = "zoom";
    
    var unitWidth = 384
    var bandInfos = [Timeline.createBandInfo({
        width: "80%",
        
        eventSource: gEventSource,
        intervalPixels: 30 * 24 * 200 / 8 / 16 / 2,
        intervalUnit: Timeline.DateTime.MONTH,
        theme: theme,
        mouseWheel: "scroll",
        zoomIndex: 8,
        zoomSteps: new Array(        //KEEP THIS FORMAT
        {
            pixelsPerInterval: unitWidth,
            unit: Timeline.DateTime.HOUR
        }, {
            pixelsPerInterval: unitWidth / 2,
            unit: Timeline.DateTime.HOUR
        }, {
            pixelsPerInterval: unitWidth / 4,
            unit: Timeline.DateTime.HOUR
        }, {
            pixelsPerInterval: unitWidth / 8,
            unit: Timeline.DateTime.HOUR
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 2,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 4,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 8,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 16,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 2,
            unit: Timeline.DateTime.MONTH
        }, //default
        {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 4,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 8,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 16,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 2,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 4,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 8,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 2,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 4,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 8,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16,
            unit: Timeline.DateTime.DECADE
        }),
    
    }), Timeline.createBandInfo({
        showEventText: false,
        width: "20%",
        eventSource: gEventSource,
        overview: true,
        
        //for zoom
        intervalPixels: 12 * 30 * 24 * 200 / 8 / 16 / 16 / 2,
        intervalUnit: Timeline.DateTime.YEAR,
        theme: theme,
        mouseWheel: "scroll",
        zoomIndex: 8,
        zoomSteps: new Array(        //KEEP THIS FORMAT
        
        {
            pixelsPerInterval: 24 * unitWidth / 8 / 2,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 4,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 8,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 24 * unitWidth / 8 / 16,
            unit: Timeline.DateTime.DAY
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 2,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 4,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 8,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 30 * 24 * unitWidth / 8 / 16 / 16,
            unit: Timeline.DateTime.MONTH
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 2,
            unit: Timeline.DateTime.YEAR
        }, //default
        {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 4,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 8,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16,
            unit: Timeline.DateTime.YEAR
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 2,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 4,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 8,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16,
            unit: Timeline.DateTime.DECADE
        }, {
            pixelsPerInterval: 10 * 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16 / 2,
            unit: Timeline.DateTime.CENTURY
        }, {
            pixelsPerInterval: 10 * 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16 / 4,
            unit: Timeline.DateTime.CENTURY
        }, {
            pixelsPerInterval: 10 * 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16 / 8,
            unit: Timeline.DateTime.CENTURY
        }, {
            pixelsPerInterval: 10 * 10 * 12 * 30 * 24 * unitWidth / 8 / 16 / 16 / 16 / 16 / 16,
            unit: Timeline.DateTime.CENTURY
        }),
    
    
    })];
    bandInfos[1].syncWith = 0;
    bandInfos[1].highlight = true;
    tl = Timeline.create(document.getElementById("my-timeline"), bandInfos);
}


//use MD5 encoding
function MD5(stringValue){
    return (dojox.encoding.digests.MD5(stringValue, dojox.encoding.digests.outputTypes.Base64));
}

//将CalendarId中的一部分抽取出来作为category的id
function generateCategoryId(calendarId){
    var start = calendarId.indexOf("/full/");
    var categoryId = calendarId.substring(start + 6, calendarId.length);
    return categoryId;
}

//统一categoryTitle的长度
function unifyLength(categoryTitle)
{
	var length = categoryTitle.length;
	var i1,n = 0;
    for (i1 = 0;i1 < length;i1++) 
	{
        if (categoryTitle.charCodeAt(i1) < 0 || categoryTitle.charCodeAt(i1) > 255) 
            n++; //全角字符    
    }
	length = length + n;
	if(length < 12)          //将长度统一为12，和日历对齐
	{
		var i2;
		for(i2 = 1;i2 <= (12 - length);i2++)
		{
			categoryTitle = categoryTitle + " &nbsp";    //加 .
		}
	}
	return categoryTitle;
		
}

//author:pengpai
//edit the category

function editCategory(e){
    var targetId = e.currentTarget.id;
    var categoryId = targetId.substring(5, targetId.length);
    //var categoryName = dijit.byId(categoryId).label;
    var categoryName = Cache.Calendars.getById(categoryId).getTitle().getText();
	
    // Create the calendar service object
    var calendarService = new google.gdata.calendar.CalendarService('TimeStamp-Service');
    
    // The default "owncalendars" feed is used to update existing calendar
    // entry from the authenticated user
    //TODO: owncalendars只包含自己有own权限的日历,而allcalendars包含所有的
    //var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';
    var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
    // This callback method that will be called when getOwnCalendarsFeed() returns feed data
    var callback = function(result){
        // Obtain the array of CalendarEntry
        var entries = result.feed.entry;
        
        // Flag to indicate whether a match is found
        var calendarFound = false;
        var isOwn = false;
        var categoryEntry;
        for (var i = 0; i < entries.length; i++) {
            var calendarEntry = entries[i];
            
            // The first matched is located!
            if (calendarEntry.getTitle().getText() == categoryName) {
                calendarFound = true;
                if (calendarEntry.getAccessLevel().getValue() == "owner") {
                    isOwn = true;
                }
                categoryEntry = calendarEntry;
                currentEditEntry = calendarEntry;
                break;
            }
        }
        // If no matched calendar is found, print this message
        if (!calendarFound) {
            alert('没有找到分类 ' + categoryName + ", 也许您没有编辑权限.");
            log('Cannot find calendar with title starts with: ' + categoryName);
            return;
        }
        
        var editDialog = dijit.byId('categoryDialog');
        editDialog.titleNode.innerHTML = "编辑分类";
        editDialog.setAttribute("execute", onUpdateCategory);
        
        //如果不是own权限，只允许编辑名称，其他的disable掉
        //modified by pengpai 2008.11.24
        if (!isOwn) {
			editDialog.titleNode.innerHTML = "查看分类";
        	editDialog.setAttribute("execute", onViewCategory);
			dojo.byId("categoryTitle").disabled = "true";
            dojo.byId("summary").disabled = "true";
            dojo.byId("location").disabled = "true";
            dojo.byId("sharing").disabled = "true";
        }
		else
		{
			editDialog.titleNode.innerHTML = "编辑分类";
        	editDialog.setAttribute("execute", onUpdateCategory);	
		}

        dojo.byId("oldTitle").value = categoryName;
        dojo.byId("categoryTitle").value = categoryName;
        var summary;
        if (categoryEntry.getSummary()) {
            summary = categoryEntry.getSummary().getText();
        }
        else {
            summary = "";
        }
        dojo.byId("summary").value = summary;
        var locations = categoryEntry.getLocations();
        for (var i = 0; i < locations.length; i++) {
            dojo.byId("location").value += locations[i].valueString;
            if (i != locations.length - 1) {
                dojo.byId("location").value += ";";
            }
        }
        //TODO: 权限问题
        //dojo.byId("")
        editDialog.show();
    }
    
    // Error handler to be invoked when getOwnCalendarsFeed() or updateEntry()
    // produces an error
    var handleError = function(error){
        log(error);
    }
    
    // Submit the request using the calendar service object
    calendarService.getAllCalendarsFeed(feedUri, callback, handleError);
    
}

//show the message
function notifyUser(content){
    dojo.byId('msgInner').innerHTML += content;
    setTimeout(function hideLoader(){
        var msg = dojo.byId('msg');
        dojo.fadeOut({
            node: msg,
            duration: 500,
            onEnd: function(){
                msg.style.display = "none";
            }
        }).play();
    }, 250);
}

//修改页面上分类相关的信息：分类名称
function updateCaterogyNameInPage(categoryId, newTitle){
	var title = unifyLength(newTitle);
    dijit.byId(categoryId).setLabel(title);
}

//重置编辑分类的对话框
function resetCategoryDialog(){
    dojo.byId("oldTitle").value = "";
    dojo.byId("categoryTitle").value = "";
    dojo.byId("summary").value = "";
    dojo.byId("location").value = "";
    //TODO: 权限的值
    //dojo.byId("oldTitle").value = "";
}

//查看分类
function onViewCategory()
{
    //重置编辑分类的对话框
    resetCategoryDialog();	
}

//update the category
function onUpdateCategory(){
    var elements = arguments[0];
    var oldTitle = elements.oldTitle;
    var newTitle = elements.categoryTitle;
    var summary = elements.summary;
    var locations = elements.location;
    var oldEntry = currentEditEntry;
    if (newTitle == "") {
        alert("分类名称不能为空!");
    }
    else {
        //calendar title
        if (newTitle != oldTitle) {
            oldEntry.setTitle(google.gdata.Text.create(newTitle));
        }
        //calendar summary
        var oldSummary;
        if (oldEntry.getSummary()) {
            oldSummary = oldEntry.getSummary().getText();
        }
        else {
            oldSummary = "";
        }
        if (summary != oldSummary) {
            oldEntry.setSummary(google.gdata.Text.create(summary));
        }
        //calendar locations
        var locationArray = locations.split(";");
        var locationParam = new Array();
        for (var i = 0; i < locationArray.length; i++) {
            var where = new google.gdata.Where();
            where.setLabel(locationArray[i]);
            where.setValueString(locationArray[i]);
            locationParam.push(where);
        }
        oldEntry.setLocations(locationParam);
        
        // Create the calendar service object
        var calendarService = new google.gdata.calendar.CalendarService('TimeStamp-Services');
        
        // The default "owncalendars" feed is used to update existing calendar
        // entry from the authenticated user
        //var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';
        var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
        var callback = function(result){
            log("calendar " + oldTitle + " updated!");
        
            //修改页面上相应的分类
            var categoryId = generateCategoryId(oldEntry.getId().getValue());
            updateCaterogyNameInPage(categoryId, newTitle);
			
			//修改cache
			Cache.Calendars.add(result.entry);
            //notify the user
            notifyUser("保存修改");
            
            //重置编辑分类的对话框
            resetCategoryDialog();
        }
        var handleError = function(error){
            log(error);
            alert(error);
        }
        oldEntry.updateEntry(callback, handleError);
    }
}

//在页面上隐藏已删除的分类
function delCategoryInPage(){
    var containerId = "container_" + generateCategoryId(currentEditEntry.getId().getValue());
    var containerNode = dojo.byId(containerId);
    if (containerNode) {
        containerNode.parentNode.removeChild(containerNode);
    }
}

//删除共享分类
//TODO:其实可以整合在deleteCategory中的，可是cache有问题，先这样解决
function delSharedCategory(e)
{
    var targetId = e.currentTarget.id;
    var categoryId = targetId.substring(4, targetId.length);
    //var categoryId = "category_" + categoryNameEncode;
    orignalCategoryNameEncode = categoryId;
    //var categoryName = dijit.byId(categoryId).label;
    var cacheCalendar = Cache.Calendars.getById(categoryId);
    var categoryName = cacheCalendar.getTitle().getText();
	
    // Create the calendar service object
    var calendarService = new google.gdata.calendar.CalendarService('TimeStamp-Service');
    
    // The default "owncalendars" feed is used to update existing calendar
    // entry from the authenticated user
    //TODO: owncalendars只包含自己有own权限的日历,而allcalendars包含所有的
    //var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';
    var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
    // This callback method that will be called when getOwnCalendarsFeed() returns feed data
    var callback = function(result){
        // Obtain the array of CalendarEntry
        var entries = result.feed.entry;
        
        // Flag to indicate whether a match is found
        var calendarFound = false;
        for (var i = 0; i < entries.length; i++) {
            var calendarEntry = entries[i];
            
            // The first matched is located!
            if (calendarEntry.getTitle().getText() == categoryName) {
                calendarFound = true;
                currentEditEntry = calendarEntry;
                if (confirm("确认删除分类" + "\"" + categoryName + "\"？")) {
                    // Delete the matched calendar
                    calendarEntry.deleteEntry(delCallback, handleError);
                }
                
                break;
            }
        }
        // If no matched calendar is found, print this message
        if (!calendarFound) {
            alert('没有找到分类 ' + categoryName + ", 也许您没有删除权限.");
            log('Cannot find calendar with title starts with: ' + categoryName);
            return;
        }
        
    }
    
    var delCallback = function(){
        log("calendar " + categoryName + " delelted!");
        //删除页面上的分类
        delCategoryInPage();
        //提示用户
        notifyUser("已保存修改");
    }
    
    // Error handler to be invoked when getOwnCalendarsFeed() or updateEntry()
    // produces an error
    var handleError = function(error){
        log(error);
    }
    
    // Submit the request using the calendar service object
    calendarService.getAllCalendarsFeed(feedUri, callback, handleError);
	
}

//author:pengpai
//delete the category
function deleteCategory(e){
    var targetId = e.currentTarget.id;
    var categoryId = targetId.substring(4, targetId.length);
    //var categoryId = "category_" + categoryNameEncode;
    orignalCategoryNameEncode = categoryId;
    //var categoryName = dijit.byId(categoryId).label;
	var cacheCalendar = Cache.Calendars.getById(categoryId);
    var categoryName = cacheCalendar.getTitle().getText();
	
    // Create the calendar service object
    var calendarService = new google.gdata.calendar.CalendarService('TimeStamp-Service');
    
    // The default "owncalendars" feed is used to update existing calendar
    // entry from the authenticated user
    //TODO: owncalendars只包含自己有own权限的日历,而allcalendars包含所有的
    var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';
    //var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
    // This callback method that will be called when getOwnCalendarsFeed() returns feed data
    var callback = function(result){
        // Obtain the array of CalendarEntry
        var entries = result.feed.entry;
        
        // Flag to indicate whether a match is found
        var calendarFound = false;
        for (var i = 0; i < entries.length; i++) {
            var calendarEntry = entries[i];
            
            // The first matched is located!
            if (calendarEntry.getTitle().getText() == categoryName) {
                calendarFound = true;
                currentEditEntry = calendarEntry;
                if (confirm("确认删除分类" + "\"" + categoryName + "\"？")) {
                    // Delete the matched calendar
                    calendarEntry.deleteEntry(delCallback, handleError);
                }
                
                break;
            }
        }
        // If no matched calendar is found, print this message
        if (!calendarFound) {
            alert('没有找到分类 ' + categoryName + ", 也许您没有删除权限.");
            log('Cannot find calendar with title starts with: ' + categoryName);
            return;
        }
        
    }
    
    var delCallback = function(){
        log("calendar " + categoryName + " delelted!");
        //删除页面上的分类
        delCategoryInPage();
        //提示用户
        notifyUser("已保存修改");
    }
    
    // Error handler to be invoked when getOwnCalendarsFeed() or updateEntry()
    // produces an error
    var handleError = function(error){
        log(error);
    }
    
    // Submit the request using the calendar service object
    calendarService.getAllCalendarsFeed(feedUri, callback, handleError);
}

//get category info by name, in google's entry form
function getInfoByCategoryName(name){
    for (var i = 0; i < calendarEntries.length; i++) {
        if (calendarEntries[i].getTitle().getText() == name) {
            return calendarEntries[i];
        }
    }
}


function onToggleButtonClick(e)
{
	selectedCategoryIds = [];
	selectedCategories = [];
    dijit.registry.byClass("dijit.form.ToggleButton").forEach(function(widget){
	    if (widget.checked == true) {
	        selectedCategoryIds.push(widget.id);
	    }
	});
	Cache.Events.showEventsOfCalendar(selectedCategoryIds);
}
//隐藏分类列表
function hideCategoryCtl(){
    document.getElementById("categoryCtl").style.display = "none";
}

//在页面上显示新建的分类
function createCategoryInPage(containerId, categoryId, categoryTitle){
    var categoryCtl = dojo.byId(containerId);
    //var categoryNameEncode = MD5(title);
    
    //for each calendar entry
    var container = dojo.doc.createElement("div");
    container.setAttribute("id", "container_" + categoryId);
    categoryCtl.appendChild(container);
    
    //for toggle button
    var toggleDiv = dojo.doc.createElement("div");
	//toggleDiv.setAttribute("width",30);
    container.appendChild(toggleDiv);
    
    //var categoryId = "category_" + categoryNameEncode;
	
	//统一长度
	categoryTitle = unifyLength(categoryTitle);
    var params = {
        id: categoryId,
        name: categoryId,
        label: categoryTitle,
        //checked: "checked",//modify by ning @ 2008.12.20
        iconClass: "dijitCheckBoxIcon",
        onClick: onToggleButtonClick
    };
    var togglerButton = new dijit.form.ToggleButton(params, toggleDiv);
    
    //for dropdown menu
    var setDiv = dojo.doc.createElement("div");
    container.appendChild(setDiv);
    var dropDownMenuParms = {
        label: ""
    };
    var setButton = new dijit.form.DropDownButton(dropDownMenuParms, setDiv);
    
    //for menu
    var menuDiv = dojo.doc.createElement("div");
    setDiv.appendChild(menuDiv);
    var menuParams = {
        id: "menu_" + categoryId
    };
    var menu = new dijit.Menu(menuParams, menuDiv);
    
    //for editing
    var editParams = {
        id: "edit_" + categoryId,
        label: "编辑",
        iconClass: "dijitEditorIcon dijitEditorIconCopy",
        onClick: editCategory
    };
    menu.addChild(new dijit.MenuItem(editParams));
    
    //for sharing
//    var shareParams = {
//        id: "share_" + categoryId,
//        label: "共享设置",
//        iconClass: "dijitEditorIcon dijitEditorIconBold"
//    };
//    menu.addChild(new dijit.MenuItem(shareParams));
//    
    //for deleting
    var delParams = {
        id: "del_" + categoryId,
        label: "删除",
        iconClass: "dijitEditorIcon dijitEditorIconCut",
        onClick: deleteCategory
    };
    menu.addChild(new dijit.MenuItem(delParams));
    menu.startup();
    setButton.dropDown = menu;
}

//在页面上创建属于订阅的分类
function createSharedCategoryInPage(containerId, categoryId, categoryTitle)
{
    var categoryCtl = dojo.byId(containerId);
    
    //for each calendar entry
    var container = dojo.doc.createElement("div");
    container.setAttribute("id", "container_" + categoryId);
    categoryCtl.appendChild(container);
    
    //for toggle button
    var toggleDiv = dojo.doc.createElement("div");
	//toggleDiv.setAttribute("width",30);
    container.appendChild(toggleDiv);
    
	//统一长度
	categoryTitle = unifyLength(categoryTitle);
    var params = {
        id: categoryId,
        name: categoryId,
        label: categoryTitle,
        //checked: "checked",
        iconClass: "dijitCheckBoxIcon",
        onClick: onToggleButtonClick
    };
    var togglerButton = new dijit.form.ToggleButton(params, toggleDiv);
    
    //for dropdown menu
    var setDiv = dojo.doc.createElement("div");
    container.appendChild(setDiv);
    var dropDownMenuParms = {
        label: ""
    };
    var setButton = new dijit.form.DropDownButton(dropDownMenuParms, setDiv);
    
    //for menu
    var menuDiv = dojo.doc.createElement("div");
    setDiv.appendChild(menuDiv);
    var menuParams = {
        id: "menu_" + categoryId
    };
    var menu = new dijit.Menu(menuParams, menuDiv);
    
    //for editing
    var editParams = {
        id: "edit_" + categoryId,
        label: "查看",
        iconClass: "dijitEditorIcon dijitEditorIconCopy",
        onClick: editCategory
    };
    menu.addChild(new dijit.MenuItem(editParams));
      
    //for deleting
    var delParams = {
        id: "del_" + categoryId,
        label: "删除",
        iconClass: "dijitEditorIcon dijitEditorIconCut",
        onClick: delSharedCategory
    };
    menu.addChild(new dijit.MenuItem(delParams));
    menu.startup();
    setButton.dropDown = menu;	
}

//创建新的分类
function onCreateCategory(){
    var elements = arguments[0];
    if (elements.categoryTitle == "") {
        alert("分类名称不能为空!");
        return;
    }
    
    // Create the calendar service object
    var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
    
    // The default "owncalendars" feed is used to insert calendar to the logged-in user
    var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';
    
    // Create an instance of CalendarEntry, representing the new calendar
    var entry = new google.gdata.calendar.CalendarEntry();
    
    // Set the calendar title
    entry.setTitle(google.gdata.Text.create(elements.categoryTitle));
    
    // Set the calendar summary
    var summary = new google.gdata.Text();
    summary.setText(elements.summary);
    entry.setSummary(summary);
    
    //    // Set the calendar timezone
    //    var timeZone = new google.gdata.calendar.TimeZoneProperty();
    //    timeZone.setValue('America/Los_Angeles');
    //    entry.setTimeZone(timeZone);
    
    // Set the calendar location
    var locations = new Array();
    if (elements.location) {
        locations = elements.location.split(";");
    }
    else {
        locations = [];
    }
    
    var locationArray = new Array();
    for (var i = 0; i < locations.length; i++) {
        var where = new google.gdata.Where();
        where.setLabel(locations[i]);
        where.setValueString(locations[i]);
        locationArray.push(where);
    }
    //entry.addLocation(where);
    entry.setLocations(locationArray);
    
    // Set the calendar to be visible in the Google Calendar UI
    var hidden = new google.gdata.calendar.HiddenProperty();
    hidden.setValue(false);
    entry.setHidden(hidden);
    
    // Set the color that represent this calendar in the Google Calendar UI
    //    var color = new google.gdata.calendar.ColorProperty();
    //    color.setValue('#2952A3');
    //    entry.setColor(color);
    
    // The callback method that will be called after a successful
    // insertion from insertEntry()
    var callback = function(result){
        log("calendar " + elements.categoryTitle + " created!");
        //在页面上显示新建的分类
        var categoryId = generateCategoryId(result.entry.getId().getValue());
        createCategoryInPage("ownCategoryCtl", categoryId, elements.categoryTitle);
		//更新cache
		Cache.Calendars.add(result.entry);
        //提示用户
        notifyUser("已保存修改");
    }
    
    // Error handler will be invoked if there is an error from insertEntry()
    var handleError = function(error){
        log(error);
    }
    
    // Submit the request using the calendar service object
    calendarService.insertEntry(feedUri, entry, callback, handleError, google.gdata.calendar.CalendarEntry);
}

//显示创建分类对话框
function createCategory(){
    resetCategoryDialog();
    var createDialog = dijit.byId('categoryDialog');
    createDialog.titleNode.innerHTML = "创建分类";
    createDialog.setAttribute("execute", onCreateCategory);
    createDialog.show();
}

//author:pengpai
//display the category list
function showCategoryCtl(){
    var categoryCtl = dojo.byId("categoryCtl");
    
    //有owner权限的分类
    var ownCategoryDiv = dojo.doc.createElement("div");
	ownCategoryDiv.setAttribute("class", "calendarCtl");
    ownCategoryDiv.setAttribute("id", "ownCategoryCtl");
    categoryCtl.appendChild(ownCategoryDiv);
    
    var title = dojo.doc.createElement("div");
	title.setAttribute("class", "calendarCtlTitle");
    title.innerHTML = "我的分类</br>";
    ownCategoryDiv.appendChild(title);
    //    var titleParams = {id: "categoryCtlTitle", title: "我的分类"};
    //    var titlePane = new dijit.TitlePane(titleParams, categoryCtl);
    
    //添加分类链接
    var addLinkDiv = dojo.doc.createElement("div");
    addLinkDiv.innerHTML = "<span><a href='javascript:createCategory()'>新建分类</a><span>";
    ownCategoryDiv.appendChild(addLinkDiv);
    
    //分类列表
    for (var i = 0; i < ownCalendarEntries.length; i++) {
        var categoryId = generateCategoryId(ownCalendarEntries[i].getId().getValue());
        var categoryTitle = ownCalendarEntries[i].getTitle().getText();
        createCategoryInPage("ownCategoryCtl", categoryId, categoryTitle);// modify by ning @ 2008-11-18
    }
    
    //共享分类
    var otherCategoryDiv = dojo.doc.createElement("div");
	otherCategoryDiv.setAttribute("class", "calendarCtl");
    otherCategoryDiv.setAttribute("id", "otherCategoryCtl");
    categoryCtl.appendChild(otherCategoryDiv);
    
    var otherTitle = dojo.doc.createElement("div");
	otherTitle.setAttribute("class", "calendarCtlTitle");
    otherTitle.innerHTML = "共享分类</br>";
    otherCategoryDiv.appendChild(otherTitle);
    //    var titleParams = {id: "categoryCtlTitle", title: "我的分类"};
    //    var titlePane = new dijit.TitlePane(titleParams, categoryCtl);
    
    //分类列表
    for (i = 0; i < otherCalendarEntries.length; i++) {
        var categoryId = generateCategoryId(otherCalendarEntries[i].getId().getValue());
        var categoryTitle = otherCalendarEntries[i].getTitle().getText();
        createSharedCategoryInPage("otherCategoryCtl", categoryId, categoryTitle);// modify by ning @ 2008-11-18
    }
}

//dojo.addOnLoad(showCategoryCtl);
//var doc = document.getElementById("test").ownerDocument;
//SimileAjax.Graphics.createMessageBubble(doc);


